#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <ifaddrs.h>
#include <stdbool.h>
#include <arpa/inet.h>

#include "./OLED/bmp.h"
#include "./OLED/oled.h"

char* getIPAddress() {
    struct ifaddrs *ifap, *ifa;
    struct sockaddr_in *sa;
	char *ipStr = NULL;
    getifaddrs(&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr && ifa->ifa_addr->sa_family != AF_INET)
			continue;
		if(strcmp(ifa->ifa_name,"br-lan"))
			continue;
        sa = (struct sockaddr_in *)ifa->ifa_addr;
		ipStr = malloc(strlen(inet_ntoa(sa->sin_addr))+1);
		strcpy(ipStr, inet_ntoa(sa->sin_addr));
    }
    freeifaddrs(ifap);
	return ipStr;
}

void timerHandler(int signum) {
    if (signum == SIGALRM) {
		static unsigned int timeCount = 0;
		static bool fistStartUp = true;
		timeCount++;
		if( (timeCount > 360) || (fistStartUp == true) ){
			char *ipStr = NULL;
			fistStartUp = false;
			timeCount = 0;
			ipStr = getIPAddress();
			OLED_ShowString(24,0,(unsigned char *)ipStr,8,1);
			OLED_Refresh();
			free(ipStr);
		}
		else{
			OLED_ShowNum(8,16,timeCount,3,8,1);
			OLED_Refresh();
		}
        alarm(1);
    }
}

int main(){
	printf("oled!!!!\n");
	sleep(20);
	OLED_Init();
	OLED_DisplayTurn(1);
	OLED_ColorTurn(0);
	OLED_ShowPicture(0,0,128,64,Logo,1);
	OLED_Refresh();
	sleep(5);

	OLED_Clear();
	OLED_ShowString(0,0,(unsigned char *)"IP:",8,1);
	OLED_Refresh();

	signal(SIGALRM, timerHandler);
	alarm(1);

	while(pause());
	return 0;
}
